﻿using System;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Newtonsoft.Json;

namespace eLearning.DosenView
{
    public partial class PerkuliahanPage : PhoneApplicationPage
    {
        private DetailMatkul perkuliahan;
        
        public PerkuliahanPage()
        {
            InitializeComponent();
        }

        private void LoadPerkuliahanDosen()
        {
            DetailMatkul find = new DetailMatkul();
            find.Creator = (Dosen)SavedUser.Instance.User.ConvertUser();
            LoadPerkuliahan(false, JsonConvert.SerializeObject(find));
            pivotPerkuliahan.SelectedIndex = 0;
        }

        private void LoadPerkuliahan(bool search, string json)
        {
            string url = null;

            if (search)
                url = Config.Instance.PERKULIAHAN_SERVICE_URL() + Config.FIND_ACTION_KEY;
            else
                url = Config.Instance.PERKULIAHAN_SERVICE_URL() + Config.PERKULIAHAN_DOSEN_VIEW_KEY;

            string urlformat = string.Format("{0}&{1}", url, Guid.NewGuid().ToString());
            Uri uri = new Uri(urlformat, UriKind.Absolute);

            WebClient webClient = new WebClient();
            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            if (search)
            {
                webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(findPerkuliahan_UploadStringCompleted);
            }
            else
            {
                webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(listPerkuliahan_UploadStringCompleted);
            }
            webClient.UploadStringAsync(uri, "POST", json);
        }

        private void findPerkuliahan_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled || e.Error != null)
                {
                    MessageBox.Show("Message : " + e.Result);
                    return;
                }

                DetailMatkulList list = JsonConvert.DeserializeObject<DetailMatkulList>(e.Result);
                if (list != null && list.Count > 0)
                {
                    listPerkuliahan.ItemsSource = list;
                    pivotPerkuliahan.SelectedIndex = 0;
                }
                else
                {
                    listPerkuliahan.ItemsSource = null;
                    MessageBox.Show("No data found");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void listPerkuliahan_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Cancelled || e.Error != null)
                {
                    MessageBox.Show("Message : " + e.Result);
                    return;
                }

                DetailMatkulList list = JsonConvert.DeserializeObject<DetailMatkulList>(e.Result);
                listPerkuliahan.ItemsSource = list;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void listPerkuliahan_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                perkuliahan = (DetailMatkul)e.AddedItems[0];

                // reset selection of ListBox
                ((ListBox)sender).SelectedIndex = -1;
                NavigateToDetail(perkuliahan);
            }

        }

        private void NavigateToDetail(object selectedItem)
        {
            Utility.GotoPage(this, "/View/Dosen/PerkuliahanDetailPage.xaml");
            FrameworkElement root = Application.Current.RootVisual as FrameworkElement;
            root.DataContext = selectedItem;
        }
        
        private void addButton_Click(object sender, EventArgs e)
        {
            Utility.GotoPage(this, "/View/Dosen/PerkuliahanFormPage.xaml");
            FrameworkElement root = Application.Current.RootVisual as FrameworkElement;
            root.DataContext = null;
        }
        
        private void searchButton_Click(object sender, EventArgs e)
        {
            pivotPerkuliahan.SelectedIndex = 1;
        }

        private void buttonSearch_Click(object sender, RoutedEventArgs e)
        {
            if (textBoxKeyword.Text.Length < 1)
            {
                MessageBox.Show("Keyword is empty.");
                return;
            }
            DetailMatkul find = new DetailMatkul();
            MataKuliah matkul = new MataKuliah();
            matkul.Nama = textBoxKeyword.Text;
            find.Matkul = matkul;
            find.Creator = (Dosen)SavedUser.Instance.User.ConvertUser();

            LoadPerkuliahan(true, JsonConvert.SerializeObject(find));
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            LoadPerkuliahanDosen();
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            if (e.NavigationMode == System.Windows.Navigation.NavigationMode.Back)
            {
                Utility.GotoPage(this, "/View/Dosen/DashboardPage.xaml");
            }
        }
        
        private void refreshButton_Click(object sender, EventArgs e)
        {
            LoadPerkuliahanDosen();
        }
                
    }
}